package com.auction.service.impl;


import cn.hutool.crypto.digest.MD5;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.auction.service.ALiMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class ALiMsgServiceImpl implements ALiMsgService {
    @Value("${accessKeyId}")
    private String accessKeyId;

    @Value("${accessKeySecret}")
    private String accessKeySecret;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void sendMsg(String mobile) {
        Config config = new Config()
                //这里修改为我们上面生成自己的AccessKey ID
                .setAccessKeyId(accessKeyId)

                //这里修改为我们上面生成自己的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        Client client = null;
        try {
            client = new Client(config);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        int code = (int) (Math.random()*10000);
        String md5Mobile = MD5.create().digestHex(mobile);
        stringRedisTemplate.opsForValue().set("mobileCode:"+md5Mobile, String.valueOf(code),5, TimeUnit.MINUTES);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName("拍卖平台")//短信签名
                .setTemplateCode("SMS_475750496")//短信模板
                .setPhoneNumbers(mobile)//这里填写接受短信的手机号码
                .setTemplateParam("{\"code\":\""+code+"\"}");//验证码
        // 复制代码运行请自行打印 API 的返回值
        try {
            client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
